import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import window from '@ohos.window';
import dataPreferences from '@ohos.data.preferences';

export default class EntryAbility extends UIAbility {



  onCreate(want, launchParam) {
    hilog.info(0x0000, 'HD_GB', '%{public}s', 'Ability onCreate');
  }

  onDestroy() {
    hilog.info(0x0000, 'HD_GB', '%{public}s', 'Ability onDestroy');
  }

  onWindowStageCreate(windowStage: window.WindowStage) {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'HD_GB', '%{public}s', 'Ability onWindowStageCreate');


    try {
      dataPreferences.getPreferences(this.context, 'mystore', function (err, val) {
        if (err) {
          console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
          return;
        }

        try {
          let promise = val.get('startup', 'default');
          promise.then((data) => {
            hilog.info(0x0000, 'HD_GB', '%{public}s', data);
          }).catch((err) => {
            hilog.info(0x0000, 'HD_GB', '%{public}s', err);
          })
        } catch(err) {
          hilog.info(0x0000, 'HD_GB', '%{public}s', err);
        }

        globalThis.preferences = val;
        console.info("Succeeded in getting preferences.");
      })
    } catch (err) {
      console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
    }


    try {
      let promise = window.getLastWindow(this.context);
      promise.then((data) => {
        globalThis.windowClass = data // 赋值给全局变量windowClass
        hilog.error(0x0000, 'HD_GB', 'Failed to load the content. Cause: %{public}s', '成功');
      }).catch((err) => {
        hilog.error(0x0000, 'HD_GB', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
      });
    } catch (exception) {
      console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(exception));
    }

    windowStage.loadContent('pages/Splash', (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'HD_GB', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'HD_GB', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');

    });
  }

  onWindowStageDestroy() {
    // Main window is destroyed, release UI related resources
    hilog.info(0x0000, 'HD_GB', '%{public}s', 'Ability onWindowStageDestroy');
  }

  onForeground() {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  }

  onBackground() {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  }
}
